pato2ids = [:]

new File (args[0]).splitEachLine("\t") { splits ->
  if ( splits.size() > 1 ) {
    if (!pato2ids.containsKey(splits[0].trim())) {
      pato2ids[splits[0].trim()] = new TreeSet<String>()
      pato2ids[splits[0].trim()].addAll(splits[1..-1])
    } else println "double def for mp: " + splits[0].trim()
  } 
}

// println pato2ids["PATO:0001472"]

new File (args[1]).splitEachLine("\t") { splits ->
  if ( splits.size() > 1 ) {
    def mp_id = splits[0].trim()
    def ts = new TreeSet<String>()
    def pato = new TreeSet<String>()
    boolean added = false

    splits[1..-1].each { s -> 
      if (s.startsWith("PATO:")) pato.add(s)
      else ts.add(s)
    }

/*
    if ( splits[0].equals("MP:0003766")) {
      println mp_id
      println ts
      println pato
    }
*/    
    if ( pato.size() > 1 ) {
      pato2ids.each { p ->
        def common = pato.grep(p.value)

        if ( common.size() == pato.size()) {
          // println "y"
          ts.add(p.key) 
          added = true
        }
      }
    }

/*
    if ( splits[0].equals("MP:0003766")) {
      println mp_id
      println ts
      println pato
    }
*/    

    print mp_id + "\t" + ts.join("\t")
    if (!added && (ts.size() > 0)) print "\t" + pato.join("\t")
    else if (!added && (ts.size() == 0)) print pato.join("\t")
    print "\n" 
  }
}

